from exchange_manager import ExchangeManager
from common_symbols import CommonSymbolsManager
from arbitrage_monitor import ArbitrageMonitor
from order_monitor import OrderMonitor
from database_manager import DatabaseManager
from logs import setup_logger
import asyncio
from loguru import logger
import argparse

async def main():
    """主程序入口"""
    db_manager = None
    exchange_manager = None
    arbitrage_monitor = None
    
    try:
        # 解析命令行参数
        parser = argparse.ArgumentParser(description='套利监控系统')
        parser.add_argument('--enable-trading', action='store_true', help='启用自动交易')
        args = parser.parse_args()
        
        # 设置日志
        logger = setup_logger()
        logger.info("=== 开始运行套利监控系统 ===")
        logger.info(f"自动交易: {'启用' if args.enable_trading else '禁用'}")
        
        # 初始化数据库管理器
        db_manager = DatabaseManager()
        
        # 初始化交易所管理器
        exchange_manager = ExchangeManager()
        # 加载市场数据以获取精度
        success = await exchange_manager.load_all_markets()
        if not success:
            logger.error("加载市场数据失败")
            return
        
        # 获取共同交易对
        symbols_manager = CommonSymbolsManager(exchange_manager)
        common_symbols = await symbols_manager.update_common_symbols()
        logger.info(f"共有 {len(common_symbols)} 个共同交易对")
        
        # 启动套利监控
        logger.info("开始运行套利监控")
        arbitrage_monitor = ArbitrageMonitor()
        await arbitrage_monitor.start(common_symbols)

        # 启动订单监控
        # order_monitor = OrderMonitor()
        # await order_monitor.start()
        
    except Exception as e:
        logger.error(f"程序运行出错: {str(e)}")
    finally:
        # 关闭所有资源
        if arbitrage_monitor:
            await arbitrage_monitor.stop()
        if exchange_manager:
            await exchange_manager.close_all_exchanges()
        if db_manager:
            db_manager.close()
        logger.info("程序已退出")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("程序被用户中断")
    except Exception as e:
        logger.error(f"程序异常退出: {str(e)}")

    #  运行命令
    #  python main.py --enable-trading
